class CVSAbstract
  include Simplicity
  #~ require 'fileutils'
  #~ include FileUtils

  @@Known_cvs = [:ss]

  # cvs_type - name of one of known cvs systems (:ss, :svn)
  # cvs_info - hash with various parametrs like
  # {:location => '\\\\p-server\\base3',
  #  :user => 'some_user',
  #  :pass => 'some_pass'}
  def initialize(cvs_type, cvs_info, log_filename = 'cvs.log')
    raise "unknown cvs sys: '#{cvs_type}'" if ! @@Known_cvs.include? cvs_type
    @cvs_type = cvs_type
    @cvs_info = cvs_info
    #~ self.send( @cvs_type.to_s + '_set_env', @cvs_info )

    begin
      t = File.new(log_filename, 'a')
      t.close
    end
    raise "can't open log file: '#{log_filename}'" if ! File.writable?(log_filename)
    @log_filename = log_filename

    # if @locked == true don't perform any get operations, wait
    @locked = false
  end

  def get_files(cvs_location, local_dir)
    self.send( (@cvs_type.to_s + '_get_files').to_sym, cvs_location, local_dir )
  end

  def checkin_file( cvs_name, local_name )
    self.send( (@cvs_type.to_s + '_checkin_file').to_sym, cvs_name, local_name )
  end
private
  def ss_set_env(cvs_info)
    raise "username needed" if (cvs_info.has_key? :user) and (! (cvs_info[:user].length > 0))
    raise "user password needed" if (cvs_info.has_key? :pass) and (! (cvs_info[:pass].length > 0))

    ENV['SSDIR'] = cvs_info[:location]
    ENV['SSUSER'] = cvs_info[:user]
    ENV['SSPWD'] = cvs_info[:pass]
  end

  def ss_get_files(cvs_location, local_dir, recursive = true)
    while @locked
      sleep 1
    end
    @locked = true

    # operations
    if local_dir.length > 0
      mkdir_p(local_dir)
      raise "someth wrong with local_dir : '#{local_dir}'" if ! File.directory? local_dir
    end

    cmd = %Q{ss get "#{cvs_location}" -I-Y #{recursive ? "-R" : ""} -GWR -GL#{win_path local_dir} 2>>&1 1>>#{@log_filename}} #  -GWS
    ss_set_env(@cvs_info)
    begin
      system cmd if ! $options[:dont_get] or puts "skipping"
    rescue
      raise "error while performing: '#{cmd}'"
    end

    @locked = false
  end

  def ss_checkin_file( cvs_name, local_name )
    ss_set_env(@cvs_info)
    puts Dir.pwd
    # checkout file without getting
    cmd = %Q{ss checkout "#{cvs_name}" -GL#{win_path local_name} -G- -I-Y >checkout.log}
    puts cmd
    system cmd if ! $options[:dont_get]

    cmd = %Q{ss checkin "#{cvs_name}" -GL#{win_path local_name} -GWR -GCK -GTU -I-Y -CBuildMachine}
    puts cmd
    system cmd if ! $options[:dont_get]
  end
end

# test

if $0 == __FILE__
  ca = CVSAbstract.new( :ss,
                        { :location => '\\\\p-server\\base3',
                          :user => 'barablin',
                          :pass => 'qazxswm85ssv' }
                       )

  ca.get_files('$/Tools/BuildTool', 'BuildTool/')
end
